package com.crazymaker.demo.drinkTea;

import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.schedulers.Schedulers;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DrinkTeaJob
{


    private static boolean waterOk;
    private static boolean cupOk;
    private static CountDownLatch downLatch = new CountDownLatch(2);


    public static void main(String args[]) throws InterruptedException
    {

        log.info("开始准备..... " );
        HotWaterJob hotJob = new HotWaterJob();
        WashCupJob washJob = new WashCupJob();
        Observable<Boolean> waterObservable = hotJob.observable();
        Observable<Boolean> washObservable = washJob.observable();

        waterObservable
                .subscribeOn(Schedulers.io())
                .subscribe(
                        result -> hotFinished(result),
                        throwAble -> log.error("烧水失败，没茶喝了!" ));

        washObservable
                .subscribeOn(Schedulers.io())
                .subscribe(
                        result -> washFinished(result),
                        throwAble -> log.error("清洗茶杯失败，没茶喝了!" ));

        doDrink();
    }

    private static void washFinished(Boolean result)
    {
        if (result == true)
        {
            cupOk = result;
        } else
        {
            return;
        }
        if (cupOk)
        {
            log.info("杯子清洗好了" );
        }
        downLatch.countDown();
    }

    private static void hotFinished(boolean result)
    {
        waterOk = result;
        if (waterOk)
        {
            log.info("水烧好了" );
        } else
        {
            return;
        }
        downLatch.countDown();

    }

    public static void doDrink() throws InterruptedException
    {

        downLatch.await(100, TimeUnit.SECONDS);
        if (cupOk && waterOk)
        {
            log.info("泡茶喝" );
        } else
        {
            log.error("喝茶失败" );
        }

    }
}
